package com.bondex.charter.controller;

import com.bondex.charter.po.CharterReqSiForBusinessListReq;
import com.bondex.charter.po.CutOffBillCreatesVO;
import com.bondex.charter.pojo.DataCount;
import com.bondex.charter.pojo.OrderInfo4List;
import com.bondex.charter.pojo.SearchParam;
import com.bondex.charter.service.ListService;
import com.bondex.charter.service.SIService;
import com.bondex.charter.service.TdJsonService;
import com.bondex.global.pojo.PageTableParamT;
import com.bondex.global.pojo.ResultT;
import com.bondex.global.utils.JacksonUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 台账页面使用接口
 * Created by JD on 2021/09/14.
 */
@Controller
@RequestMapping("/List")
@Tag(name = "List")
public class ListController extends BaseWebController {

	@Autowired
	private ListService listService;

	@Autowired
	private TdJsonService tdJsonService;

	@Autowired
	private SIService sIService;

	@Operation(summary = "列表查询")
	@RequestMapping(value = "/getList", method = RequestMethod.POST, produces = "application/json;charset=utf-8;")
	@ResponseBody
	public ResultT<List<OrderInfo4List>> getList(HttpServletRequest request, HttpServletResponse response
			, @Parameter(description = "查询条件") @RequestBody PageTableParamT<SearchParam> param
	) {
		return listService.getList(param);
	}

	@Operation(summary = "状态值统计")
	@RequestMapping(value = "/getStatusCount", method = RequestMethod.POST)
	@ResponseBody
	public String getStatusCount(HttpServletRequest request, HttpServletResponse response
			, @Parameter(description = "查询条件") PageTableParamT<SearchParam> param
	) {
		ResultT<Map<String, Object>> oResult = listService.getStatusCount(param);
		return JacksonUtil.writeValue(oResult);
	}

	@Operation(summary = "数据统计")
	@RequestMapping(value = "/getDataCount", method = RequestMethod.POST, produces = "application/json;charset=utf-8;")
	@ResponseBody
	public ResultT<DataCount> getDataCount(HttpServletRequest request, HttpServletResponse response
			, @Parameter(name = "Token", description = "CAS登录后的Token信息") @RequestHeader String token
			, @Parameter(description = "查询条件（预留入参，不必传递值）") @RequestBody(required = false) PageTableParamT<SearchParam> param
	) {
		if (StringUtils.isBlank(token)) {
			token = getTokenInRequest(request);
		}
		return listService.countData(param, token);
	}

	@Operation(summary = "合票")
	@RequestMapping(value = "/combineOrder", method = RequestMethod.POST)
	@ResponseBody
	public String combineOrder(HttpServletRequest request, HttpServletResponse response
			, @Parameter(description = "查询条件") PageTableParamT<SearchParam> param
	) {
		ResultT<Map<String, Object>> oResult = listService.getStatusCount(param);
		return JacksonUtil.writeValue(oResult);
	}

	@Operation(summary = "拆票")
	@RequestMapping(value = "/splitOrder", method = RequestMethod.POST)
	@ResponseBody
	public String splitOrder(HttpServletRequest request, HttpServletResponse response
			, @Parameter(description = "查询条件") PageTableParamT<SearchParam> param
	) {
		ResultT<Map<String, Object>> oResult = listService.getStatusCount(param);
		return JacksonUtil.writeValue(oResult);
	}

	/*
	@Operation(summary = "导出")
	@RequestMapping(value = "/export", method = RequestMethod.POST)
	@ResponseBody
	public String export(HttpServletRequest request, HttpServletResponse response) {
		return "";
	}*/

	@Operation(summary = "格式单下载")
	@RequestMapping(value = "/downloadDraft", method = RequestMethod.GET)
	@ResponseBody
	public void downloadDraft(HttpServletRequest request, HttpServletResponse response, String orderNo) {
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd,MM,yyyy,HHmmss");
		String fileName = "DRAFT_" + orderNo + "_" + dtf.format(now) + ".pdf";
		OutputStream outputStream = null;
		try {
			// 防止中文乱码
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.setContentType("application/octet-stream;charset=UTF-8");
			outputStream = new BufferedOutputStream(response.getOutputStream());
			//	InputStream inputStream = ytInteractiveService.newDownLoadPDF(id,bookingNo);
			File file = tdJsonService.buildCutOff(orderNo);
			FileInputStream inputStream = new FileInputStream(file);
			byte[] buff = new byte[4096];
			int n;
			while ((n = inputStream.read(buff)) != -1) {
				outputStream.write(buff, 0, n);
			}
			outputStream.flush();
			inputStream.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Operation(summary = "提单下载")
	@RequestMapping(value = "/downloadBL", method = RequestMethod.GET)
	@ResponseBody
	public void downloadBL(HttpServletRequest request, HttpServletResponse response, String orderNo) {
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd,MM,yyyy,HHmmss");
		String fileName = orderNo + "_" + dtf.format(now) + ".pdf";
		OutputStream outputStream = null;
		try {
			// 防止中文乱码
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.setContentType("application/octet-stream;charset=UTF-8");
			outputStream = new BufferedOutputStream(response.getOutputStream());
			//InputStream inputStream = ytInteractiveService.newDownLoadPDF(id,bookingNo);
			File file = tdJsonService.formalCutOff(orderNo);
			FileInputStream inputStream = new FileInputStream(file);
			byte[] buff = new byte[4096];
			int n;
			while ((n = inputStream.read(buff)) != -1) {
				outputStream.write(buff, 0, n);
			}
			outputStream.flush();
			inputStream.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Operation(summary = "SOC打标操作")
	@RequestMapping(value = "/handleSocMarking", method = RequestMethod.POST)
	@ResponseBody
	public String handleSocMarking(HttpServletRequest request, HttpServletResponse response
			, @RequestBody CharterReqSiForBusinessListReq req) {
		return JacksonUtil.writeValue(sIService.handleSocMarking(req));
	}

	@Operation(summary = "甩货")
	@RequestMapping(value = "/handleDumpGoods", method = RequestMethod.POST)
	@ResponseBody
	public String handleDumpGoods(HttpServletRequest request, HttpServletResponse response
			, @RequestBody CharterReqSiForBusinessListReq req) {
		return JacksonUtil.writeValue(sIService.handleDumpGoods(req));
	}

	@Operation(summary = "台账——格式单生成")
	@RequestMapping(value = "/cutOffSI", method = RequestMethod.POST)
	@ResponseBody
	public ResultT cutOffBillCreates(HttpServletRequest request, HttpServletResponse response
			, @RequestBody CutOffBillCreatesVO cutOffBillCreatesVO) {
		return sIService.updateAndBillCreates(cutOffBillCreatesVO);
	}


}